<?php
/*
class BaseForm()
-------------------------------------------------------
automatically creates a form for database manipulation

*/

class BaseForm {
     var $bindtable;
     var $formvars;
     var $types;
     var $fields;
     var $labels;
     var $fieldId;
     var $retval;
     var $filters;
     var $buttonEnable;
     var $customButtons;
     var $customQuery;
     var $inputParams;
     var $navParams;
     var $pagename;
	 var $ecma;
	 var $enableform;

	function BaseForm($params,$post) {
		$this->retval = "";
		$this->filters = "";
		$this->formname = $params["formname"];
		$this->bindtable = $params["tablename"];
		$this->formvars =array();
		$this->fieldId=$this->getIdField($tbl);
		$this->buttonEnable=array("add"=>true,"edit"=>true,"delete"=>true);
		$this->customQuery=$params["customQuery"];
		$this->customButtons=$params["customButtons"];
		$this->inputParams=$params["inputParams"];
		$this->setLabels($params["labels"]);
		$this->setFields($params["fields"]);
		$this->setTypes($params["types"]);
		$this->ecma=$params["ecma"];
		$this->enableform=($params["enableform"]) ? $params["enableform"] : false;
		if($params["buttonEnable"]) $this->buttonEnable=$params["buttonEnable"];

		if($post["cmd"]=="add") {
			$this->BuildAddForm();
		}elseif ($post["cmd"]=="edit") {
			if($post["chkitm"][0]) {
				$this->BuildEditForm($post["chkitm"][0]);
			}else{
				$this->retval="<div class='error' style='color:#CC0000;'>* Please select an item.</div>";
				$this->BuildListForm(0,0);
			}
		}elseif ($post["cmd"]=="delete") {
			for ( $i=0 ; $i < count($post["chkitm"]) ; $i++ ) {
				$this->deleterow($post["chkitm"][$i]);
			}
			$this->BuildListForm(0,0);
		}elseif ($post["cmd"]=="save") {
			$error = $this->addrow($post);
			if ($error) $this->retval="<div class='error' style='color:#CC0000;'>* Found existing Rate Name</div>";
			$this->BuildListForm(0,0);
		}elseif ($post["cmd"]=="update") {
			$this->updaterow($post["idsel"]);
			$this->BuildListForm(0,0);
		}else{
			$this->BuildListForm(0,0);
		}
	}

     function addVar($newvar) {
          $this->formvars[] = $newvar;
     }

     function setFields($x) {
          $this->fields=$x;
     }

     function setPagename($x) {
          $this->pagename=$x;
     }

     function setInputParams($x) {
          $this->inputParams=$x;
     }

     function setlabels($x) {
          $this->labels=$x;
     }

     function setTypes($x) {
          $this->types=$x;
     }

     function setFilters($x) {
          $this->filters=$x;
     }

     function BindTable($tbl) {
          $this->bindtable=$tbl;
     }

     function setCustomQuery($x) {
          $this->customQuery=$x;
     }

     function setCustomButtons($x) {
          $this->customButtons=$x;
     }

     function setNavParams($x) {
          $this->navParams=$x;
     }

     function BuildAddForm() {
          $this->retval .= "<table  class='tablesorter'>\n";
          $fieldcount = count($this->labels);
          $this->retval.="<tr><th colspan=2 height='20px' class='bgHeader'>". strtoupper($this->formname) ."</th></tr>\n";
          for($i=0;$i < $fieldcount; $i++) {
               $this->retval .= "<tr>\n";
              $this->retval .= "<td width='10%' nowrap=true valign='top' />";
               if($this->types[$i]!=='hidden') {
                  if ($this->types[$i]=='checkbox') $this->retval .= $this->labels[$i][0];
                  else $this->retval .= $this->labels[$i];
               }
               $this->retval .= "</td>\n";
               $this->retval .= "<td>";
               $this->retval .= $this->getItemFormLayout($i);
               $this->retval .= "</td>\n";
               $this->retval .= "<tr>\n";
          }
          $this->retval.="<tr><td colspan=2 align='right'><input type=button class='buttons' value=back onClick='history.go(-1);'>&nbsp;<input type=submit class='buttons' name=cmd value=save /></td></tr>\n";
          $this->retval .= "</table>\n";
     }

     function BuildEditForm($id) {
          $sql = "select * from ". $this->bindtable ." where ". $this->getIdField($this->bindtable) ."='". $id ."'";
          //echo $sql;die();
          $res = mysql_query($sql);
          $row=mysql_fetch_array($res);
          $this->retval .= "<table class='tablesorter'>\n";
          $fieldcount = count($this->labels);
          $this->retval.="<tr><th colspan=2 height='20px' class='bgHeader'>". strtoupper($this->formname) ."</th></tr>\n";
          for($i=0;$i < $fieldcount; $i++) {
               $this->retval .= "<tr>\n";
               $this->retval .= "<td width='10%' nowrap=true  valign='top' />";
               if($this->types[$i]!=='hidden') {
                  if ($this->types[$i]=='checkbox') $this->retval .= $this->labels[$i][0];
                  else $this->retval .= $this->labels[$i];
               }
               $this->retval .= "</td>\n";
               $this->retval .= "<td>";
               if($this->types[$i]==='dropdowntreelist' || $this->types[$i]==='dropdownlist' || $this->types[$i]==='enum' || $this->types[$i]==='dropdown'){
                    $thisval = $this->fields[$i][0];
               }elseif($this->types[$i]==='checkbox'){
                    $thisval = $this->fields[$i][1];
               }else{
                    $thisval = $this->fields[$i];
               }
               $this->retval .= $this->getItemFormLayout($i , $row[ $thisval ]);
               $this->retval .= "</td>\n";
               $this->retval .= "<tr>\n";
          }
          $this->retval.="<tr><td colspan=2 align='right'>";
          $this->retval.="<input type=hidden name=idsel value='$id'>";
          $this->retval.="<input type=button class='buttons' value=back onClick='history.go(-1);'>&nbsp;<input type=submit class='buttons' name=cmd value=update></td></tr>\n";
          $this->retval .= "</table>\n";
     }

     function getItemFormLayout($idx,$val="") {
          $retval="";
          switch($this->types[$idx]) {
               case 'text':
				$newname = "new" .str_replace(" ","_",$this->labels[$idx]);
                    $retval .= "<input type='" .$this->types[$idx]. "'  name='$newname' id='$newname' ";
                    $retval .= " value='$val' ";
                    $retval .= (isset($this->inputParams[$idx])) ? $this->inputParams[$idx] : "";
                    $retval .= " style='width:30%'>\n";
                    break;
               case 'password':
				$newname = "new" .str_replace(" ","_",$this->labels[$idx]);
                    $retval .= "<input type='" .$this->types[$idx]. "'  name='$newname' id='$newname' ";
                    $retval .= " value='$val' ";
                    $retval .= (isset($this->inputParams[$idx])) ? $this->inputParams[$idx] : "";
                    $retval .= " style='width:100%'>\n";
                    break;
               case 'textarea':
				  $newname = "new" .str_replace(" ","_",$this->labels[$idx]);
                    $retval .= "<textarea name='$newname' id='$newname' ";
                    $retval .= (isset($this->inputParams[$idx])) ? $this->inputParams[$idx] : "";
                    $retval .=" style='width:100%'>$val</textarea>\n";
                    break;
               case 'dropdownlist':
                    $ddsql = " select * from " . $this->fields[$idx][1];
                    $ddres = mysql_query($ddsql) or die($ddsql);
				   $newname = "new" .str_replace(" ","_",$this->labels[$idx]);
                    $retval .= "<select name='$newname' id='$newname' ";
                    $retval .= (isset($this->inputParams[$idx])) ? $this->inputParams[$idx] : "";
                    $retval .= ">\n" ;
                    $retval.="<option value=0></option>";
                    while($ddrow=mysql_fetch_array($ddres)) {
                         $retval .= "<option value='" .$ddrow[0]. "' ";
                         $retval .= ( $ddrow[$this->fields[$idx][2]] == $val) ? " selected " : "";
                         $retval .= ">" . $ddrow[$this->fields[$idx][3]] . "</option>\n";
                    }
                    $retval .= "</select>\n";
                    break;
				case 'dropdowntreelist':
                    $ddsql = " select * from " . $this->fields[$idx][1];
                    $ddres = mysql_query($ddsql) or die($ddsql);
				   $newname = "new" .str_replace(" ","_",$this->labels[$idx]);
                    $retval .= "<select name='$newname' id='$newname' ";
                    $retval .= (isset($this->inputParams[$idx])) ? $this->inputParams[$idx] : "";
                    $retval .= ">\n" ;
                    $retval.="<option value=0></option>";
                    while($ddrow=mysql_fetch_array($ddres)) {
                         $retval .= "<option value='" .$ddrow[0]. "' ";
                         $retval .= ( $ddrow[$this->fields[$idx][2]] == $val) ? " selected " : "";
                         $retval .= ">" . $ddrow[$this->fields[$idx][3]] . "</option>\n";
                    }
                    $retval .= "</select>\n";
                    break;
               case 'enum':
                    $val_arr = $this->fields[$idx][1];
				  $newname = "new" .str_replace(" ","_",$this->labels[$idx]);
                    while(list($num,$value)=each($val_arr)) {
                         $retval.="&nbsp;<input type='radio' name='$newname' id='$newname' ";
                         $retval.=($value===$val || $value=='Yes') ? " checked " : "";
                         $retval.=" value='". $value ."'>" . $value;
                    }
                    break;
               case 'date':
			   $newname = "new" .str_replace(" ","_",$this->labels[$idx]);
                    $retval .= "<input type='" .$this->types[$idx]. "' name='$newname' id='$newname' ";
                    $retval .= (strlen($val)) ? " value='$val' " : " value='". date("Y-m-d H:i:s") ."' ";
                    $retval .= (isset($this->inputParams[$idx])) ? $this->inputParams[$idx] : "";
                    $retval .= " style='width:100%'>\n";
                    break;
               case 'hidden':
			   $newname = "new" .str_replace(" ","_",$this->labels[$idx]);
                    $retval .= "<input type='" .$this->types[$idx]. "' name='$newname' id='$newname' ";
                    $retval .= " value='$val' ";
                    $retval .= (isset($this->inputParams[$idx])) ? $this->inputParams[$idx] : "";
                    $retval .= " style='width:100%'>\n";
                    break;
               case 'file':
			   $newname = "new" .str_replace(" ","_",$this->labels[$idx]);
                    $retval .= "<input type='" .$this->types[$idx]. "'  name='$newname' id='$newname' ";
                    $retval .= " value='$val' ";
                    $retval .= (isset($this->inputParams[$idx])) ? $this->inputParams[$idx] : "";
                    $retval .= " style='width:100%'>\n";
                    break;
                case 'checkbox':
                $val_arr = $this->fields[$idx];
                //echo "<pre>";print_r($val_arr);die();
				  $newname = "new" .str_replace(" ","_",$this->labels[$idx]);
				            if (isset($_POST['cmd']) && $_POST['cmd'] == "edit") {
                        $dowValDb = explode("|",$val);
                    }
                    //echo "<pre>";print_r($dowValDb);die();
                    while(list($num,$value)=each($val_arr[2])) {
                         $retval.="&nbsp;<input type='checkbox' name='$num' id='$num' ";
                         if (isset($_POST['cmd']) && $_POST['cmd'] == "edit") {
                            if(in_array($value,$dowValDb)) $retval .= " checked "; 
                         }
                         else $retval.=($value===$val) ? " checked " : "";
                         $retval.=" value='". $value ."'>" . $value."<br />";           
                    }
                    break;
                case 'dropdown':
                $val_arr = $this->fields[$idx][1];
				  $newname = "new" .str_replace(" ","_",$this->labels[$idx]);
				            $retval .= "<select name='$newname' id='$newname' ";
                    //$retval .= (isset($this->inputParams[$idx])) ? $this->inputParams[$idx] : "";
                    $retval .= ">\n" ;
                    $retval.="<option value=0></option>";
                    while(list($num,$value)=each($val_arr)) {
                         $retval .= "<option value='" .$num. "' ";
                         $retval.=($num==$val) ? " selected " : "";
                         $retval.=">" . $value . "</option>\n";
                    }
                    $retval .= "</select>\n";                    
                    break;
          }
          return $retval;
     }

     function getIdField() {
          $sql = " select * from " . $this->bindtable;
          $res = mysql_query($sql);
          return mysql_field_name($res,0);
     }

     function BuildListForm($start,$maxrows) {
          if(strlen($this->customQuery)) {
               $sql.=$this->customQuery;
          }else{
               $sql = "select * from " . $this->bindtable;
               $sql.= $this->filters;
          }
          $res = mysql_query($sql) or die(mysql_error());
          $numrows = mysql_num_rows($res);

          unset($res);
          if($maxrows==0) $maxrows=$numrows;
          if (isset($_GET['start'])) $start=$_GET['start'];
          else $start=0;
          $limit=$start+5;
          $sql.=" limit $start, $limit ";
          //echo $sql;die();
          $res = mysql_query($sql) or die(mysql_error());

          $navstring = $this->getNavString($start,5,$maxrows);


		      $this->retval .= $this->buildcommands();

          $this->retval .= "<div><table id='myTable' class='tablesorter'>\n";
          $fieldcount = count($this->labels);
          $colspan =$fieldcount + 2;
          $rowcount = mysql_num_rows($res);
		  $this->retval.="<thead>";
          if($rowcount > 0) {
               $this->retval.="<tr class='bgHeader'>";
				$this->retval.="<th class='{sorter: false}' width='20px'><input type='checkbox' id='chkall' /></th>";
               for($i=0; $i < $fieldcount; $i++) {
                    if (is_array($this->labels[$i])) $this->retval.="<th>".$this->labels[$i][0]."</th>"; 
                    else $this->retval.="<th>".$this->labels[$i]."</th>";
               }
               $this->retval.="</tr>";
			   $this->retval.="</thead>";
               $ridx=0;
               $bgnum=3;
			   $this->retval.="<tbody>";
               while($row=mysql_fetch_array($res)) {
                    $bgcolornum=$bgnum % 2;
                    if ($bgcolornum==1) $txtBgColor="#FAFAFA"; 
                    else $txtBgColor="#F8FFFF"; 
                    $this->retval.="<tr style='background-color:".$txtBgColor."'>";
					$this->retval.="<td><input type='checkbox' name='chkitm[]' value='{$row[$this->fieldId]}' class='cbitem'></td>";
                    for($i=0; $i < $fieldcount; $i++) {
                         $this->retval.="<td align='center'>";
                         if($this->types[$i]=='dropdownlist') {
                              $fieldname=$this->fields[$i][0];
                              $fktable=$this->fields[$i][1];
						   $fkkey = $this->fields[$i][2];		
                              $fkfield=$this->fields[$i][3];
                              $this->retval.=  $this->getForeignKeyValue($this->bindtable,$fieldname, $fktable,$fkkey,$fkfield,$row[$fieldname]);
                         }elseif($this->types[$i]==='enum'){
                              $this->retval.=$row[$this->fields[$i][0]];
                         }elseif($this->types[$i]==='checkbox'){  
                              $this->retval.=$row[$this->fields[$i][1]];
                         }elseif($this->types[$i]==='dropdown'){
                              if ($row[$this->fields[$i][0]]<=11 && $row[$this->fields[$i][0]]>=1) {
                                $this->retval.=$row[$this->fields[$i][0]]."AM";
                              } elseif($row[$this->fields[$i][0]]==24) {
                                $this->retval.=($row[$this->fields[$i][0]]-12)."AM";
                              } elseif($row[$this->fields[$i][0]]>=13 && $row[$this->fields[$i][0]]<=23) {
                                $this->retval.=($row[$this->fields[$i][0]]-12)."PM";
                              } else {
                                $this->retval.=($row[$this->fields[$i][0]])."PM";
                              }
                         }else{
                              $this->retval.=$row[$this->fields[$i]];
                         }
                         $this->retval.="</td>";
                    }
                    $this->retval.="</tr>\n";
                    $bgnum++;
               }
          }else{
               $this->retval.="<tr><td colspan=$colspan align=center>:: no records found ::</td></tr>\n";
          }
			$this->retval.="</tbody></table></div>";
			$this->retval.="<div align='right' style='font-size:8pt;font-family:arial; width:100%;' >$numrows records found.</div>";
			if($rowcount > 0) $this->retval.= "<div align='right'>".$navstring."</div>";
		$this->retval.=$this->getpager();
     }

     function addrow($input) {
          $field_str="";
		  $error=false;
		  $resultRateName = mysql_query("SELECT * FROM ". $this->bindtable ." WHERE rate_name='".trim($_POST['newRate_Name'])."'");
		  $existRateName = mysql_num_rows($resultRateName);
		  if ($existRateName<1) {
          while(list($name,$varr)=each($this->fields)) {
               $field_str.= ( strlen ($field_str ) ) ? "," : "";
               if(is_array($varr)) {
                    if ($varr[0] == "checkbox") {
                        $field_str .= $varr[1];
                    }
                    else $field_str.=$varr[0];
               } else {
                    $field_str.=$varr;
               }
          }
          $sql = " insert into " . $this->bindtable . "($field_str)  values (";
          reset($_POST);
          for($i=0;$i < count($this->labels); $i++) {
               $sql .= ($i) ? "," : "";
               if (is_array($this->labels[$i])) {
                  $sql .= "'";
                  foreach($this->labels[$i][1] as $key_label => $value_label) {
                  //echo "<pre>";print_r($this->labels[$i]);die();
                      if (isset($_POST[$value_label]) && $_POST[$value_label]!="") {
                          $newValue .= $_POST[$value_label]."|";
                      }
                  }
                  $sql .= substr($newValue,0,-1);
                  $sql .= "'";
               }
               else $sql .= "'" . $_POST[ ("new" . str_replace(" ","_",$this->labels[$i]) ) ]. "'" ;

          }
          $sql.= ")";
          //echo "<pre>";print_r($_POST);die();
          //echo $sql;die();
          mysql_query($sql) or die($sql.mysql_error());
		 }
		 else {
		 	$error=true;
		 }
		 return $error;
     }

     function updaterow($input) {
          $newValue = "";
          $sql = " update " . $this->bindtable . " set   ";
          for($i=0;$i < count($this->fields); $i++) {
               $sql .= ($i) ? "," : "";
               if (is_array($this->fields[$i])) {
                    if ($this->fields[$i][0] == "checkbox") {
                        $thisval = $this->fields[$i][1];
                    }
                    else $thisval = $this->fields[$i][0];
               }
               else $thisval =  $this->fields[$i];
               //$thisval = (is_array($this->fields[$i])) ? $this->fields[$i][0] : $this->fields[$i];
               if (is_array($this->labels[$i])) {
                  foreach($this->labels[$i][1] as $key_label => $value_label) {
                  //echo "<pre>";print_r($this->labels[$i]);die();
                      if (isset($_POST[$value_label]) && $_POST[$value_label]!="") {
                          $newValue .= $_POST[$value_label]."|";
                      }
                  }
                  $newValue = substr($newValue,0,-1);
                  $sql .= $thisval . "='" .$newValue. "'";
               }
               else $sql .= $thisval . "='" . $_POST[ "new" . str_replace(" ","_",$this->labels[$i]) ] . "'" ;
          }
          $sql.= " where ". $this->getIdField($this->bindtable) . "='$input'";
          //echo $sql;die();
          mysql_query($sql) or die($sql);
     }

	  function deleterow($input) {
          $sql = " delete from " . $this->bindtable  ;
          $sql.= " where ". $this->getIdField($this->bindtable) . "='$input'";
          mysql_query($sql) or die($sql);
     }

	 function actionsuccess ($mesg) {

	 }

     function getForeignKeyValue($srcTable,$srcField,$foreignTable,$foreignKey='',$foreignField='',$thisvalue){
		
          $gsql= "select a.$foreignField as retval from $foreignTable a, $srcTable b where ";
          $gsql.= " a.$foreignKey=b.$srcField and ";
          $gsql.= " b.$srcField=$thisvalue";
          $gres = mysql_query($gsql) or die($gsql);
		 $num = mysql_num_rows($gres);
		 if($num) {
			$grow=mysql_fetch_array($gres);
			return $grow["retval"];
		}else{
			return " -- ";
		}
     }

     function getNavString($start,$maxrows,$numrows) {

               $currpage=1;
               $currcount=0;
               if(is_array($this->navParams)) {
                    while(list($id,$val)=each($this->navParams)) {
                         $tmp = "$id=$val&";
                    }
               }
			   $retval.="<font style='font-size:11px;'>Page(s)</font>";
               while( $currcount < $numrows ) {
                    if (empty($this->pagename) && $this->pagename=="") $this->pagename=$_SERVER['PHP_SELF'];
                    $retval.=" <a href='" . $this->pagename;
                    $retval.= (stristr($this->pagename,"?")) ? "&" : "?";
                    $retval.= $tmp."start=$currcount'>$currpage</a>&nbsp;";
                    $currcount+=$maxrows;
                    $currpage++;
               }

          return $retval;
     }

	function buildcommands () {
		$tmpstr = "<div style='float:left; padding-top:5px;'><strong style='color:#678197'>RATES</strong></div><div style='float:right;'>";
		foreach ( $this->buttonEnable as $key => $value) {
			if($value) {
				$tmpstr .="<input class='buttons' type='submit' name='cmd' value='$key' ";
				if($key=="delete") $tmpstr .=" onclick='return confirm(\"Delete selected items?\")' ";
				$tmpstr .="/> ";
			}
		}

		//---> custom buttons
          if( is_array($this->customButtons) ) {
               for($j=0; $j < count($this->customButtons); $j++) {
                    $tmpstr.="<input type='submit' class='buttons' name='cmd' value='" . $this->customButtons[$j] . "'>";
               }
          }

		$tmpstr .= "</div><div style='clear:both;'>&nbsp;</div>";
		return $tmpstr;
	}

	 function getpager() {
		 $tmp = '
		<div id="pager" class="pager">
			<form>
				<img src="addons/pager/icons/first.png" class="first"/>
				<img src="addons/pager/icons/prev.png" class="prev"/>
				<input type="text" class="pagedisplay"/>
				<img src="addons/pager/icons/next.png" class="next"/>
				<img src="addons/pager/icons/last.png" class="last"/>
				<select class="pagesize">
					<option selected="selected" value="10">10</option>
					<option    value="50">50</option>
					<option  value="100">100</option>
					<option value="200">200</option>
				</select>
			</form>
		</div>';
		//return $tmp;
	 }

/** output methods **/

	function getHtml() {
		$tmp = "
		<link rel='stylesheet' href='../../../css/admin.css' type='text/css' />
		<script type='text/javascript' src='../../../js/jquery.js'></script>
		<script type='text/javascript' src='../../../js/jquery.dimensions.js'></script>
		<script type='text/javascript' src='../../../js/ui.tablesorter.js'></script>
		<script type='text/javascript' src='../../../js/validate_rates_form.js'></script>
		<script>
		$(document).ready(function()
			{
				$('#myTable')
					.tablesorter({headers: { 0: {sorter:false}}});
				$('#chkall').click(function(){ $('.cbitem').attr('checked', ($(this).attr('checked')) ? true : false  ) });
				{$this->ecma}
			}
		);
		</script>
		";
		
		if($this->enableform) {
			return $tmp . "<div id='wrapper'>
      <form method='post' action='".$this->pagename."' name='form' onSubmit='return validate_rates_form(this);' />" .$this->retval ."</form> 
      </div>" . $script;
		}else{
			return $tmp . $this->retval ;
		}
		
	}

	 function showForm() {
          echo $this->getHtml();
     }
}

?>